<?php
namespace Admin\Controller;
use Common\Utils\Constants;
use Think\Controller;
use Think\Model;

header("Content-Type:text/html; charset=utf-8");

class BaseController extends Controller
{
    protected $baseModel;
    /**
     * 判断是否登录
     * @param $baseModel 处理当前表的基本Model
     * BaseController constructor.
     */
    public function __construct($baseModel)
    {
        parent::__construct();
        $user = session('admin');
        if (!isset($user)) {
        $this->redirect('/Admin/Login/loginUI');
    }
        $url = MODULE_NAME .'/'. CONTROLLER_NAME . '/' . ACTION_NAME;
//        $url = CONTROLLER_NAME . '/' . ACTION_NAME;
//        var_dump($url);
//        $url = CONTROLLER_NAME;
        if(!$this->isAdmin()) {
            $PrivilegeModel = D('Privilege');
            $admin = D('Admin')->where(array('id' => $user['id']))->find();
            $privilege = $PrivilegeModel->getPrivilegeByUrlAndAdmin($url, $admin['id']);
//        var_dump($PrivilegeModel->getLastSql());
            if (!$privilege) {
                $this->display('Public/noPrivilege');
                exit;
            }
        }
//        $user = D('User')->find($user['id']);
        if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest") {

        }else{
//            var_dump($PrivilegeModel->getLastSql());
            $this->assign('user', $user);
            $this->assign('is_admin', $this->isAdmin() ? 1 : 0);
        }
//        $this->assign('is_admin',$this->isAdmin() ? '1':'0');
        $this->baseModel = $baseModel;
    }


    protected function getAdmin(){
        $admin = session('admin');
        return $admin;
    }

    protected function isAdmin(){
        $user = $this->getAdmin();
        return $user['id'] == C('ADMIN_ID');
    }

    /**
     * 追加一个面包屑导航项目
     * @param string $name  导航项目名
     * @param string $path  导航路径
     */
    protected function bcItemPush($name, $path=''){
        $tmp = C('breadcrumb');
        $tmp[] = array('name'=>$name, 'path'=>$path);
        C('breadcrumb', $tmp);
        $this->assign('breadcrumb', $tmp);
    }

    /**
     * 跳转到添加页面
     * 通过
     * $this->assign('list', $list);
     * 添加界面要显示的数据
     */
    protected function addUI()
    {
        C('TOKEN_ON', true);//开启表单校验
        $this->display('add');
    }

    /**
     * 处理添加,向界面返回json数据
     * @param $validate=null  校验规则
     * @param $is_use_i = false 是否使用i函数
     */
    protected function add($validate = null,$is_use_i = true)
    {
        if (!$this->baseModel->autoCheckToken($_POST)) {
            // 令牌验证错误
            $this->retJson(false, '添加失败,不能重复提交表单');
        }
        if (IS_POST) {
            if($is_use_i) {
                $data = $this->baseModel->validate($validate)->create(I('post.'), 1);
            }else{
                $data = $this->baseModel->validate($validate)->create($_POST);
            }
            if (!$data)
                $this->retJson(false, $this->baseModel->getError());
            try {
                $this->baseModel->startTrans();//开启事务
                $this->doAddBefore($data);
                $success = $this->baseModel->add($data);
                $this->doAddAfter($data, $success);
                if ($success) {
                    $this->baseModel->commit();
                    $this->retJson(true, '添加成功');
                }else{
                    $this->baseModel->rollback();
                    $this->retJson(false, '添加失败');
                }
            } catch (\Exception $e) {
                $this->baseModel->rollback();
                $this->retJson(false, '添加失败' . $e->getMessage());
            }
        }
        $this->retJson(false, '添加失败,不能非法提交');
    }

    /**
     * 跳转到修改界面
     * 通过
     * $this->assign('list', $list);
     * 添加界面要显示的数据
     */
    protected function editUI()
    {
        C('TOKEN_ON', true);//开启表单校验
        $this->display('edit');
    }

    /**
     * 处理修改
     * @param $validate =array() 校验规则
     * @param $is_use_i = false 是否使用i函数
     */
    protected function edit($validate = array(),$is_use_i = true)
    {
        if (!$this->baseModel->autoCheckToken($_POST)) {
            // 令牌验证错误
            $this->retJson(false, '修改失败,不能重复提交表单');
        }
        if (!empty($_POST)) {
            if($is_use_i) {
                $data = $this->baseModel->validate($validate)->create(I('post.'), 1);
            }else{
                $data = $this->baseModel->validate($validate)->create($_POST);
            }
            if (!$data)
                $this->retJson(false, $this->baseModel->getError());
            if (empty($data)) {
                $this->retJson(false, '修改失败,数据不能为空');
            }
            $this->baseModel->startTrans();//开启事务
            $this->doEditBefore($data);
            $success = $this->baseModel->save($data);
            $this->doEditAfter($data, $success);
            if ($success || $success == 0) {
                $this->baseModel->commit();
                $this->retJson(true, '修改成功');
            }else{
                $this->baseModel->rollback();
                $this->retJson(false, '修改失败'.$success);
            }
        }
        $this->retJson(false, '修改失败,不能非法提交');
    }

    /**
     * 更新字段
     */
    public function updateField()
    {
        $id = I('id');
        $value = I('value');
        $field = I('field');
        $where['id'] = ':id';
        $bind[':id'] = $id;
        $category = $this->baseModel->where($where)->bind($bind)->find();
        $category[$field] = $value;
        $result = $this->baseModel->save($category);
        if($result){
            $this->ajaxReturn(array('success'=>true,'message'=>'修改成功'));
        }else{
            $this->ajaxReturn(array('success'=>false,'message'=>'修改失败'));
        }
    }
    /**删除
     * @param $id 删除项的id
     */
    protected function delete($id)
    {
        try {
            $this->baseModel->startTrans();//开启事务
            $this->doDeleteBefore($id);
            $this->baseModel->where('id=' . $id)->delete();
        } catch (\Exception $e) {
            $this->baseModel->rollback();//事务回滚
            $this->retJson(false, '数据删除失败'.$e->getMessage());
        }
        $this->doDeleteAfter($id);
        $this->baseModel->commit();
        $count = $this->baseModel->count();
        $this->ajaxReturn(array('check'=>true,'message'=>'数据删除成功！','count'=>$count));
//        $this->retJson(true, '数据删除成功','count',$count);
    }

    /**
     * 获取数据列表
     * @param  $list
     * @param $recordcount
     */
    protected function datalist($list = null,$recordcount = null)
    {
        if ($list == null) {
            $list = $this->baseModel->select();
        }
        if($recordcount == null || $recordcount==''){
            $recordcount = $this->baseModel->count();
        }
        $this->assign('list', $list);
        $this->assign('recordcount', $recordcount);
        $this->display('list');
    }

    /**
     *  向客户端返回json数据
     * @param $check 操作是否成功
     * @param $message 提示信息
     */
    protected function retJson($check, $message)
    {
        $json['check'] = $check;
        $json['message'] = $message;
        $this->ajaxReturn($json);
    }
    /**
     * 方法回调
     * 添加数据前的处理
     * @param $data 表单数据
     */
    protected function doAddBefore(&$data){

    }
    /**
     * 方法回调
     * 添加数据后的处理
     * @param $data 表单数据
     * @param $success 是否成功 如果成功则为主键
     */
    protected function doAddAfter($data, $success)
    {
    }

    /**
     * 方法回调
     * 在修改数据前对数据处理
     * @param $data 表单数据
     */
    protected function doEditBefore(&$data)
    {
    }

    /**
     * 方法回调
     * 修改数据后的处理
     * @param $data 表单数据
     * @param $success 是否成功
     */
    protected function doEditAfter($data, $success)
    {
    }

    protected function doDeleteBefore($id)
    {
    }

    protected function doDeleteAfter( $id)
    {
    }
}